package com.sfeir.poc.portal.gui.client.services;

import java.util.Iterator;

import com.google.gwt.user.client.Window;
import com.sfeir.poc.portal.gui.client.EventAwareClass;
import com.sfeir.poc.portal.gui.client.events.ApplicationEvent;
import com.sfeir.poc.portal.gui.client.events.ApplicationEventType;
import com.sfeir.poc.portal.gui.client.services.feed.Entrie;
import com.sfeir.poc.portal.gui.client.services.feed.Feed;
import com.sfeir.poc.portal.gui.client.services.feed.FeedListener;

/**
 * Get the feed of a spreasheet sheet from its url
 * Use to get the content
 * 
 * @author bostoen.v
 *
 */
public class WidgetService extends EventAwareClass implements FeedListener{

	public void getWidgets(String url) {
		Feed feed = new Feed();
		feed.getFeed(url + "#" + System.currentTimeMillis(), this);
	}

	public void onActionFired(ApplicationEvent event) {
		super.onActionFired(event);
		if (event.getType().equals(ApplicationEventType.GET_WIDGETS)) {
			getWidgets((String) event.getContext());
		}
	}

	public void onFailure() {
		Window.alert("Failure");	
	}

	public void onSuccess(Feed feed) {
		String result = "";

		Entrie entrie = null;
		for (Iterator<Entrie> iterator = feed.getEntries().iterator(); iterator.hasNext();) {
			entrie = (Entrie) iterator.next();
			result += "title: " + entrie.getTitle() + ", ";
			result += entrie.getContent() + "\n";
		}
		fireActionEvent(ApplicationEventType.WIDGETS_UPDATED, result);
	}
}
